package com.qf.web.filter;

import com.qf.domain.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "AutoFilter",value = "/index.jsp")
public class AutoFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    //【过滤功能】
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1.强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //2.过滤
        User user = (User) request.getSession().getAttribute("user");//通过session获取登录时存储的用户
        //已经登录就没有自动登录
        if (user != null) {
            //放行
            filterChain.doFilter(request,response);
            return;
        }
        //如果有用户
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("userInfo")){
                    String userInfo = cookie.getValue();//bbb#123456
                    //解码
                    userInfo = Base64Utils.decode(userInfo);
                    //拆分
                    String[] arr = userInfo.split("#");
                    if (arr.length==2){
                        String username = arr[0];//bbb
                        String password = arr[1];//123456
                        System.out.println(username+"  "+password);
                        UserService userService = new UserServiceImpl();
                        try {
                            User u = userService.login(username,password);//通过拆分得到的用户名密码进行登录
                            request.getSession().setAttribute("user",u);

                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println(e.getMessage());
                            //清除cookie
                            Cookie deleteCookie = new Cookie("userInfo","");
                            deleteCookie.setPath(request.getContextPath());
                            deleteCookie.setMaxAge(0);
                            response.addCookie(deleteCookie);
                        }

                    }
                }
            }
        }
        //3.放行****
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
